﻿using CommonBase;
using CommonClass;
using EnvControlLib;
using FileLib;
using Microsoft.Practices.Prism.Commands;
using SurveillanceLib;
using SurveillancePro.Base.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace ToolkitMgtModule.ViewModels
{
    /// <summary>
    /// 文件转换（AVI）
    /// </summary>
    public class ViewModel_ConvertFile : WorkspaceViewModel
    {
        #region Const Fields

        private readonly string SAVEPATH_CONVERTVIDEO;

        #endregion

        #region Private Fields

        private string _pConvertHandleByRecordFile; // 文件转换结果状态
        private string _saveConvertVideoFileName; // 保存的转换远程录像回放文件名
        private bool _isConverting; // 表示是否正在转换远程录像回放文件
        private FileDetailModel _currentConvertingFile;
        private DelegateCommand _cmdStopConvert;

        #endregion

        #region Constructor

        public ViewModel_ConvertFile()
        {
            base.ViewName = SurveillancePro.Base.Common.ViewNames.ToolkitMgtModule_ConvertFile;
            base.HeaderTitle = "文件转换";
            base.HeaderImageSource = string.Format(ConstantString.IMAGE_URL, "Question");
            base.IsShowCloseButton = Visibility.Collapsed;

            this._isConverting = false; // 未转换
            if (string.IsNullOrWhiteSpace(SurveillanceUtilities.ConvertVideoPath))
                SAVEPATH_CONVERTVIDEO = SurveillanceUtilities.USERCONFIG_CONVERTVIDEOPATH_DEFAULT;
            else
                SAVEPATH_CONVERTVIDEO = SurveillanceUtilities.ConvertVideoPath;

            this._convertVideoPath = this.SAVEPATH_CONVERTVIDEO;
            FileOperation.CreatDirectory(SAVEPATH_CONVERTVIDEO); // 创建文件夹

            ConvertFileList = new ObservableCollection<FileDetailModel>();
            ConvertFileList.CollectionChanged += OnCollectionChanged;
        }

        #endregion

        #region Base Class Overrides

        protected override void OnDispose()
        {
            _dispose();
        }

        #endregion

        #region Event Handling Methods

        void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null && e.NewItems.Count != 0)
                foreach (FileDetailModel file in e.NewItems)
                    file.PropertyChanged += this.OnFileDetailModelPopertyChanged;

            if (e.OldItems != null && e.OldItems.Count != 0)
                foreach (FileDetailModel file in e.OldItems)
                    file.PropertyChanged -= this.OnFileDetailModelPopertyChanged;
        }

        void OnFileDetailModelPopertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // Blank for now
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// 文件转换列表
        /// </summary>
        public ObservableCollection<FileDetailModel> ConvertFileList { get; set; }

        private string _convertVideoPath;
        /// <summary>
        /// 文件转换路径
        /// </summary>
        public string ConvertVideoPath
        {
            get
            {
                return _convertVideoPath;
            }
            set
            {
                if (_convertVideoPath == value) return;
                _convertVideoPath = value;
                base.OnPropertyChanged("ConvertVideoPath");
            }
        }

        private bool? _isSelectAll = false; // 初值：表示不“全选”
        /// <summary>
        /// CheckBox 是否全选
        /// <para>三态</para>
        /// </summary>
        public bool? IsSelectAll
        {
            get
            {
                return _isSelectAll;
            }
            set
            {
                _isSelectAll = value;
                base.OnPropertyChanged("IsSelectAll");


                if (ConvertFileList != null)
                {
                    foreach (FileDetailModel file in ConvertFileList)
                    {
                        if (value.HasValue)
                            file.IsSelected = value.Value;
                    }
                }
            }
        }


        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_StopConvertFileList
        {
            get
            {
                if (_cmdStopConvert == null)
                {
                    _cmdStopConvert = new DelegateCommand(_stopConvertFileList, _canStopConvertFileList);
                }
                return _cmdStopConvert;
            }
        }

        /// <summary>
        /// 列表单个项目选择时
        /// </summary>
        public ICommand Cmd_DataGridClickCheckBox
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    IsSelectAll = Utilities.SetSelectAllCheckBoxState(ConvertFileList);
                });
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// 将所选文件添加到转换列表中
        /// </summary>
        /// <param name="selectedFileList">所选文件列表</param>
        public void Add2List(List<FileDetailModel> selectedFileList)
        {
            try
            {
                if (selectedFileList == null ||
                    selectedFileList.Count <= 0)
                    return;

                FileDetailModel convertFile;
                // 去重复文件
                foreach (FileDetailModel file in selectedFileList)
                {
                    if (ConvertFileList.IndexOf(file) < 0) // 未找到已存在的项时
                    {
                        convertFile = new FileDetailModel(file.NetRecordFileInfo);
                        Utilities.CopyObject(file, convertFile);

                        ConvertFileList.Add(convertFile);
                    }
                }

                base.OnPropertyChanged("ConvertFileList");
                IsSelectAll = false; // 不全选
                _convertFirstFile(); // 文件列表改变时，判断是否需要继续转换文件
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion

        #region Private Methods

        #region DelegateCommand

        private bool _canStopConvertFileList()
        {
            return true;
        }


        /// <summary>
        /// 停止转换
        /// </summary>
        private void _stopConvertFileList()
        {
            try
            {
                List<FileDetailModel> _selectedConvertFileList; // 所选转换文件列表
                if (ConvertFileList != null && ConvertFileList.Count > 0)
                {
                    _selectedConvertFileList = ConvertFileList.Where(c => c.IsSelected).ToList(); // 获得所选转换文件列表

                    if (_selectedConvertFileList.Count <= 0)
                    {
                        AutoCloseNoticeWindow.Show("请选择要停止转换的文件！");
                        return;
                    }
                    else
                    {
                        if (_selectedConvertFileList.IndexOf(_currentConvertingFile) >= 0) // 要停止的文件中包含正在转换的文件
                        {
                            _stopConvert(); // 停止转换
                        }

                        foreach (FileDetailModel stopFile in _selectedConvertFileList)
                        {
                            ConvertFileList.Remove(stopFile);
                        }
                    }

                    _convertFirstFile(); // 文件列表改变时，判断是否需要继续转换文件
                }
                else
                    AutoCloseNoticeWindow.Show("请选择要停止转换的文件！");
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion

        #region 回调函数
        /// <summary>
        /// 文件转换回调函数
        /// </summary>
        /// <param name="nPort"></param>
        /// <param name="IMediaChangeType"></param>
        /// <param name="pUserData"></param>
        /// <param name="pbIfContinue"></param>
        /// <param name="sNewFileName"></param>
        private void _fAVIConvertCallback(int nPort, int IMediaChangeType,
            int pUserData, bool pbIfContinue, string sNewFileName)
        {
            try
            {
                if (_currentConvertingFile != null)
                {
                    //if (dwConvertSize > dwTotalSize)
                    //{
                    //    if (dwConvertSize == uint.MaxValue) // 表示转换完成
                    //    {
                    //        Application.Current.Dispatcher.Invoke((Action)(() =>
                    //        {
                    //            ConvertFileList.Remove(_currentConvertingFile); // 已转换完成，并移除首个文件
                    //        }));

                    //        dwConvertSize = 0; // 进度重置
                    //        _stopConvert(); // 停止转换，否则继续转换失败
                    //        _convertFirstFile(); // 文件列表改变时，判断是否需要继续转换文件
                    //    }
                    //    else
                    //        dwConvertSize = dwTotalSize; // 防止显示超过 100%
                    //}

                    //_currentConvertingFile.Percentage = string.Format("{0:f2} %",
                    //    100.00 * dwConvertSize / dwTotalSize); // 计算进度百分比
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }
        #endregion

        /// <summary>
        /// 开始转换
        /// </summary>
        private void _startConvert()
        {
            this._isConverting = false; // 未转换

            try
            {
                if (_currentConvertingFile == null)
                    return;

                if (_currentConvertingFile.SelectedDriver != null &&
                    _currentConvertingFile.SelectedDriver.Driver_Instance != null)
                {
                    TagModel driverTag = _currentConvertingFile.SelectedDriver;
                    _saveConvertVideoFileName = Path.Combine(SAVEPATH_CONVERTVIDEO,
                        string.Format("ConvertVideo_{0}_{1}_{2}_{3}.dav", _currentConvertingFile.DriverIP,
                        _currentConvertingFile.DriverChannel,
                        _currentConvertingFile.FileStartTime.ToString("yyyyMMddHHmmss"),
                        _currentConvertingFile.FileEndTime.ToString("yyyyMMddHHmmss"))); // 保存的文件名称

                    if (!driverTag.Driver_Instance.PlayControl("OpenFile",
                        (int)(_currentConvertingFile.DriverChannel - 1)))
                    {
                        MessageBox.Show("打开文件失败", ConstantString.MSG_COMPANY);
                        return;
                    }
                    driverTag.Driver_Instance.SetStreamOpenMode(0, "STREAME_FILE");//设置流模式
                    driverTag.Driver_Instance.PlayControl("OpenStream", 0, IntPtr.Zero, 0, (UInt32)(900 * 1024));
                    driverTag.Driver_Instance.PlayControl("Start", 0);
                    driverTag.Driver_Instance.StartAVIConvert(0, _saveConvertVideoFileName, _fAVIConvertCallback, 0);

//                    _pConvertHandleByRecordFile = driverTag.Driver_Instance.DownloadByRecordFile(
//                        driverTag.Driver_LoginID,
//                        _currentConvertingFile.NetRecordFileInfo, _saveConvertVideoFileName,
//                        _fAVIConvertCallback, IntPtr.Zero); // 按文件转换录像文件

//                    if (!string.IsNullOrWhiteSpace(_pConvertHandleByRecordFile))
//                    {
//#if DEBUG
//                        Debug.WriteLine("开始转换远程录像回放文件");
//#endif
//                        this._isConverting = true; // 转换中
//                        ConvertVideoPath = _saveConvertVideoFileName;
//                    }
//                    else
//                    {
//#if DEBUG
//                        Debug.WriteLine("转换失败！");
//#endif
//                        MessageBox.Show("转换失败！", Utilities.MSG_COMPANY);
//                    }
                }
                else
                {
                    MessageBox.Show("开始转换文件失败！", ConstantString.MSG_COMPANY);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 停止转换
        /// </summary>
        private void _stopConvert()
        {
            try
            {
                if (_currentConvertingFile == null)
                    return;

                if (!string.IsNullOrWhiteSpace(_pConvertHandleByRecordFile) &&
                    _currentConvertingFile.SelectedDriver != null &&
                    _currentConvertingFile.SelectedDriver.Driver_Instance != null)
                {
                    TagModel driverTag = _currentConvertingFile.SelectedDriver;
                    bool pStopConvertHandle = driverTag.Driver_Instance.StopDownload(
                        _pConvertHandleByRecordFile); // 停止转换录像文件

                    if (pStopConvertHandle)
                    {
#if DEBUG
                        Debug.WriteLine("停止转换远程录像回放文件成功");
#endif
                    }
                    else
                    {
#if DEBUG
                        Debug.WriteLine("转换文件保存失败！");
#endif
                        MessageBox.Show("转换文件保存失败！", ConstantString.MSG_COMPANY);
                    }
                }
                else
                {
                    MessageBox.Show("停止转换文件失败！", ConstantString.MSG_COMPANY);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            this._isConverting = false; // 未转换
        }

        /// <summary>
        /// 判断是否继续转换文件
        /// </summary>
        private void _convertFirstFile()
        {
            if (!this._isConverting && ConvertFileList.Count > 0) // 未转换
            {
                _currentConvertingFile = ConvertFileList.FirstOrDefault();
                _startConvert(); // 开始转换列表第一个文件
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        private void _dispose()
        {
            try
            {
                if (this._isConverting && _currentConvertingFile != null) // 正在转换中
                {
                    if (!string.IsNullOrWhiteSpace(_pConvertHandleByRecordFile) &&
                        _currentConvertingFile.SelectedDriver != null &&
                        _currentConvertingFile.SelectedDriver.Driver_Instance != null)
                    {
                        TagModel driverTag = _currentConvertingFile.SelectedDriver;
                        bool pStopConvertHandle = driverTag.Driver_Instance.StopDownload(
                            _pConvertHandleByRecordFile); // 停止转换录像文件

                        if (pStopConvertHandle)
                        {
#if DEBUG
                            Debug.WriteLine("停止转换远程录像回放文件成功");
#endif
                        }
                        else
                        {
#if DEBUG
                            Debug.WriteLine("转换文件保存失败！");
#endif
                        }
                    }
                }

                if (ConvertFileList != null)
                {
                    ConvertFileList.Clear();
                    ConvertFileList.CollectionChanged -= this.OnCollectionChanged;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion
    }
}
